// 国家标准数据元属性
import React from 'react';
import { Row, Col, Button, Icon, Divider, Popconfirm, message, Input, Select } from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx'; // 公共table组件
import NewAttribute from './component/NewAttribute.jsx'; // 新增数据元属性
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import 'assets/css/common.css';
import './style/index.less';

let {Option} = Select;

export default class DataElementAttribute extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [],
            tableData: [],
            total: 0,
            page: 1,
            pageSize: 10,
            headerHeight: 0,
            listID: undefined, // 表ID
            code: undefined, // 属性代码
            descripts: undefined, // 属性名称
            internalCode: undefined, // 属性内部代码
            definition: undefined, // 属性定义
            dataRange: undefined, // 值域
            standardVersion: undefined, // 国标版本
            dataCatalogueID: undefined, // 数据元目录ID
            loading: false,
            tableWidth: 0,
        };
        this.columns = [
            {
                title: '属性代码',
                dataIndex: 'code',
                align: "center",
                width: '150px'
            },
            {
                title: '属性名称',
                dataIndex: 'descripts',
                align: "center",
                width: '200px'
            },
            {
                title: '属性内部代码',
                dataIndex: 'internalCode',
                align: "center",
                width: '100px',
            },
            {
                title: '数据元目录ID',
                dataIndex: 'dataCatalogueID',
                align: "center",
                width: '100px'
            },
            {
                title: '数据元目录名称',
                dataIndex: 'dataCatalogueDesc',
                align: "center",
                width: '150px',
            },
            {
                title: '允许值',
                dataIndex: 'dataRange',
                align: "center",
                width: '200px'
            },
            {
                title: '属性定义',
                dataIndex: 'definition',
                align: "center",
                width: '400px'
            },
            {
                title: '国标版本',
                dataIndex: 'standardVersion',
                align: "center",
                width: '100px'
            },
            {
                title: '开始日期',
                dataIndex: 'startDate',
                align: "center",
                width: '100px',
            },
            {
                title: '结束日期',
                dataIndex: 'stopDate',
                align: "center",
                width: '100px'
            },
            {
                title: '创建日期',
                dataIndex: 'createdDateTime',
                align: "center",
                width: '150px'
            },
            {
                title: '最后更新人',
                dataIndex: 'updateUserDesc',
                align: "center",
                width: '100px'
            },
            {
                title: '最后更新日期',
                dataIndex: 'updateDateTime',
                align: "center",
                width: '150px'
            },
            {
                title: '操作',
                key: 10,
                align: "center",
                fixed: 'right',
                width: 130,
                render: (text, record) => (
                    <span>
                        <Icon type="edit" style={{color: '#108EE9'}}></Icon>
                        <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                        {/* 分割线 */}
                        <Divider type="vertical" />
                        <Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                            <span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
                        </Popconfirm>
                    </span>
                ),
            }
        ]
    }

    componentDidMount() {
        this.getColumnsData(); // 初始化表头数据
        this.handleQuery(); // 初始化列表数据
        this.getSelectData(); // 初始化下拉框数据
        var box = document.querySelector(".attribute-header");
		if(box){ //此处在加一层判断，更加严密，如果box存在的情况下获取
			this.setState({headerHeight: box.offsetHeight})
		}
    }

    // 获取下拉框数据
    getSelectData = () => {
        let data = {
			params: [{
                queryType:"LIST"
            }]
		}
		$http.post('urlS', this, {
			code: "06010029",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
                    this.setState({selectData: res.result})
				}
			}
		})
    }

    // 获取表头数据
    getColumnsData = () => {
        let data = {
			params: [{
				compontName: "DataElementAttribute",
				type: "C",
			}]
		}
		$http.post('urlDeault', this, {
			code: "01040073",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
                    var totalWidth = 0;
                    let obj = {
                        title: '操作',
                        key: 10,
                        align: "center",
                        fixed: 'right',
                        width: 130,
                        widthNum: 130,
                        render: (text, record) => (
                            <span>
                                <Icon type="edit" style={{color: '#108EE9'}}></Icon>
                                <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                                {/* 分割线 */}
                                <Divider type="vertical" />
                                <Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
                                <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                                    <span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
                                </Popconfirm>
                            </span>
                        )
                    }
					let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
						return {
							...item,
							widthNum: parseInt(item.width),
                            title: <div onDoubleClick={!name ? this.columnChild.onOpenModel : this.doctorAdviceHistoryColumnRef.onOpenModel}>{item.title}</div>,
						}
					}) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    filterArr.push(obj);
					for(var i = 0; i < filterArr.length; i++) {
						totalWidth += filterArr[i].widthNum;
                    }
                    this.setState({ columns: filterArr, tableWidth: totalWidth })
				}
			}
		})
    }

	columnRef = (ref) => {
		this.columnChild = ref;
	}

    // 查询
    handleQuery = () => {
        this.setState({page: 1, pageSize: 10}, () => {
            this.getTableData();
        })
    }

    // 获取表格数据
    getTableData = () => {
        this.setState({loading: true})
        let {page, pageSize, listID, code, descripts, internalCode, definition, dataRange, standardVersion, dataCatalogueID} = this.state;
		let data = {
			params: [{
                ID: listID, // 表ID
                code, // 属性代码
				descripts, // 属性名称
				internalCode, // 属性内部代码
				definition, // 属性定义
				dataRange, // 值域
                standardVersion, // 国标版本
                dataCatalogueID, // 数据元目录ID
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page
			}]
		}
		$http.post('urlS', this, {
			code: "06010005",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for(var i = 0; i < res.result.data.length; i++) {
                        res.result.data[i].key = i;
                        res.result.data[i].createdDateTime = res.result.data[i].createdDate + ' ' + res.result.data[i].createdTime;
                        res.result.data[i].updateDateTime = res.result.data[i].updateDate + ' ' + res.result.data[i].updateTime;
					}
					this.setState({ tableData: res.result.data, total: res.result.totalCount, loading: false })
					// 数据加载成功关闭loading
					this.child.handleLoading();
				} else {
					this.setState({ tableData: [], total: 0, loading: false })
					// 数据加载失败关闭loading
					this.child.handleLoading();
				}
			},
			error: function (error) {
				this.setState({ tableData: [], total: 0, loading: false }, () => {
					// 数据加载成功关闭loading
					this.child.handleLoading();
				})
			}
		})
    }
    
	// 调用公共组件的连接事件
	onRef = (ref) => {
		this.child = ref
    }

    newOnRef = (ref) => {
		this.newChild = ref
    }

	// 提供修改page和pageSize的回调函数
	compilePage(page, pageSize) {
		// 修改page，或者pageSize
		this.setState({ page: page, pageSize: pageSize }, () => {
			// 重新调用查询方法
			this.getTableData();
		})
	}

    // 表ID
    // handleListIDOnChange = e => {
    //     this.setState({listID: e.target.value})
    // }

    // 目录代码
    handleCodeOnChange = e => {
        this.setState({code: e.target.value})
    }

    // 目录名称
    handleDescriptsOnChange = e => {
        this.setState({descripts: e.target.value})
    }

    // 属性内部代码
    handleInternalCodeOnChange = e => {
        this.setState({internalCode: e.target.value})
    }

    // 属性定义
    handleDefinitionOnChange = e => {
        this.setState({definition: e.target.value})
    }

    // 值域
    handleDataRangeOnChange = e => {
        this.setState({dataRange: e.target.value})
    }

    // 国标版本
    handleStandardVersionOnChange = e => {
        this.setState({standardVersion: e.target.value})
    }

    // 数据元目录
    handleDataCatalogueIDOnChange = e => {
        this.setState({dataCatalogueID: e})
    }

    // 新目录
    handleAdd = () => {
        let obj = {
            flag: 'add'
        }
        this.newChild.showModal(obj);
    }

    // 编辑
    handleCompile = record => {
        let obj = {
            flag: 'compile',
            userInfo: record
        }
        this.newChild.showModal(obj);
    }

    // 删除
    handleDelete = record => {
        let data = {
			params: [{
				ID: record.ID
			}]
		}
		$http.post('urlADS', this, {
			code: '06010008',
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					message.success('删除成功');
                    // 刷新列表数据
                    this.getTableData();
				}
			}
		})
    }

    render() {
        let {columns, tableData, total, page, headerHeight, listID, code, descripts, internalCode, definition, dataRange, standardVersion,
            dataCatalogueID, selectData, loading, tableWidth
        } = this.state;
        // 组件所需参数
		const param = {
			// 表头配置
			columns: columns&&columns.length > 0 ? columns : this.columns,
			// 表格数据
			data: tableData,
			// 数据总条数
			total,
			// 当前页数
			page,
			// 表格的宽度
			x: columns&&columns.length > 0 ? tableWidth : 2130,
			y: store.getState().tableHeight.y + 78 - headerHeight,
            height: store.getState().tableHeight.y + 123 - headerHeight + 'px',
            loading
        }
        
        // 目录ID
        let dataCatalogueIDOption = selectData&&selectData.data&&selectData.data.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })

        return (
            <div>
                <div className="attribute-header">
                    <Row style={{ minHeight: '64px', padding: '0 24px' }}>
                        <Col span={20}>
                            {/* 表ID：<Input 
                                value={listID} 
                                onChange={this.handleListIDOnChange} 
                                style={{width: '100px', margin: '23px 6px 0 0'}}
                                placeholder="请输入"
                                onPressEnter={this.handleQuery}
                            /> */}
                            目录代码：<Input 
                                value={code} 
                                onChange={this.handleCodeOnChange} 
                                style={{width: '100px', margin: '23px 6px 0 0'}} 
                                placeholder="请输入" 
                                onPressEnter={this.handleQuery}
                            />
                            目录名称：<Input 
                                value={descripts} 
                                onChange={this.handleDescriptsOnChange} 
                                style={{width: '100px', margin: '23px 6px 0 0'}} 
                                placeholder="请输入" 
                                onPressEnter={this.handleQuery}
                            />
                            属性内部代码：<Input 
                                value={internalCode} 
                                onChange={this.handleInternalCodeOnChange} 
                                style={{width: '100px', margin: '23px 6px 0 0'}} 
                                placeholder="请输入" 
                                onPressEnter={this.handleQuery}
                            />
                            属性定义：<Input 
                                value={definition} 
                                onChange={this.handleDefinitionOnChange} 
                                style={{width: '100px', margin: '23px 6px 0 0'}} 
                                placeholder="请输入" 
                                onPressEnter={this.handleQuery}
                            />
                            <div style={{display: 'inline-block'}}>
                                值域：<Input 
                                    value={dataRange} 
                                    onChange={this.handleDataRangeOnChange} 
                                    style={{width: '100px', margin: '23px 15px 0 0'}}
                                    placeholder="请输入" 
                                    onPressEnter={this.handleQuery}
                                />
                                国标版本：<Input 
                                    value={standardVersion} 
                                    onChange={this.handleStandardVersionOnChange} 
                                    style={{width: '100px', margin: '23px 6px 0 0'}} 
                                    placeholder="请输入" 
                                    onPressEnter={this.handleQuery}
                                />
                                数据元目录： <Select
                                        showSearch optionFilterProp="seatchprop" allowClear
                                        style={{width: '100px', margin: '23px 15px 0 0'}} 
                                        placeholder="请选择"
                                        value={dataCatalogueID}
                                        onChange={this.handleDataCatalogueIDOnChange} 
                                    >
                                        {dataCatalogueIDOption}
                                    </Select>
                                <Button onClick={this.handleQuery} style={{ margin: '23px 0 20px 0', background: 'rgba(255,255,255,1)'}}>查询</Button>
                            </div>
                        </Col>
                        <Col span={4} style={{ textAlign: 'right' }}>
                            <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', marginTop: '23px'}}>新增属性</Button>
                        </Col>
                    </Row>
                </div>
                <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                <div style={{ padding: 24 }} className="table-body-height">
                    {/* handelThis将夫组件的属性与方法给子组件访问 */}
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                </div>
                <NewAttribute onRef={this.newOnRef} handleQuery={this.getTableData} selectData={selectData} /> 
				<ColumnAuthoritysModel
					clientWidth='800px'
					compontName="DataElementAttribute"
					configType="C"
					onRef={this.columnRef}
					reloadData={() => this.getColumnsData()}
				/>
            </div>
        )
    }
}